/*************************************************************
 *                  渠道公共方法                        *
 * 实现的功能
 * 加载下拉菜单
 * 选择问题的生效渠道（非模态框选择，未知问题回答显示方式）
 * @param callback 获取全部渠道后的回调
 * @param queryCallback 查询函数（点击渠道时调用）
 *
 * * 使用说明：
 * 1、html结构
 * 		用于显示选择项的标签，添加class=sourceType sourceId=-1 channelId=-1;
 * 		下拉菜单的父级ul 加上class=channel-menu
 * 2、调用方式：
 * 		setSourceFun(setdropDownList,inSrc);
 *
 * 3、发送请求时，获取channelId:$('.sourceType').attr('channelId') 以及 sourceId :$('.sourceType').attr('sourceId')
 *
 *************************************************************/


/**
 * 获取渠道的数据，
 * */
function setSourceFun(callback, queryCallback, showEle) {
	$.ajax({
		url: encodeURI('../../Configuration/listChannelValve'),
		data: {
			itemId: localStorage.getItem('sourceItemId')
		},
		success: function (data) {
			callback(data, queryCallback, showEle);
		},
		error: function(){
			throw new Error('获取渠道接口调用失败');
		}

	})
}

/**
 * 渠道展示方式不一致
 */
function SourceView(data,sourceStatus) {
	if(sourceStatus==true){
		for(var i=data.length-1;i>-1;i--){
			var data1=data[i].sourceConfigList
			for(var j=data1.length-1;j>-1;j--){
				if(data1[j].status==1){
					data1.splice(j,1)
				}
			}
			if(data1.length==0){
				data.splice(i,1)
			}
		}
	}
    this.data = data;
    this.sourceTmpArray = [];
    this.maxLength = 15;
}

SourceView.prototype = {
    createSourceView: function (dom) {
        var self = this;
        self.dom = dom;
        var tmp = '';
        self.sourceTmpArray = {};
        this.data.forEach(function (item) {
            var sourceTmpArray = '';
            tmp += '<a class="sourceItem" go="0" style="margin: 2px;" dataId=' + item.DicCode + '>' +
                '<span class="preItem">' + item.DicDesc + '<div class="preNum"></div></span>'
            if (item.sourceConfigList.length > 0) {
                tmp += '<div class="source-box hide">';
            }

            item.sourceConfigList.forEach(function (subItme, index) {
                var index = index + 1;
                if (index <= self.maxLength) {
                    tmp += '<span subgo="0" subId="' + subItme.sourceId + '">' + subItme.name + '</span>'
                } else {
                    sourceTmpArray += '<span subgo="0" subId="' + subItme.sourceId + '">' + subItme.name + '</span>';
                }
            })

            if (item.sourceConfigList.length > self.maxLength) {
                tmp += '<div class="unfoldSource" preId="' + item.DicCode + '">...</div>';
            }

            if (item.sourceConfigList.length > 0) {
                tmp += '</div>'
            }
            tmp += '</a>'

            self.sourceTmpArray[item.DicCode] = sourceTmpArray;
        });

        dom.append(tmp);

        self.addClickEvent();
    },
    addClickEvent: function () {
        var self = this;
        /**
         * 点击父渠道
         */
        this.dom.on('click', 'a.sourceItem', function (e) {
            if ($(this).attr('go') == 1 || !$(this).attr('go')) {
				$(this).attr('go', '0');
				$(this).attr('all', '0');
                $(this).removeClass('btn-primary');

                var siblingsDom = $(this).children('.source-box').children('span');
                Array.prototype.slice.call(siblingsDom).forEach(function (item) {
                    $(item).removeClass('sourceSubClass').attr('subgo', '0');
                });
            } else {
				$(this).attr('go', '1');
				$(this).attr('all', '1');
                $(this).addClass('btn-primary');
                var siblingsDom = $(this).children('.source-box').children('span');
                Array.prototype.slice.call(siblingsDom).forEach(function (item) {
                    $(item).addClass('sourceSubClass').attr('subgo', '1');
                });
            }
        });


        this.dom.on('click', '.source-box', function (e) {
            e.stopPropagation();
        })

        /**
         * 点击子渠道
         */
        this.dom.on('click', '.source-box span', function (e) {
            $(this).toggleClass('sourceSubClass');
            if ($(this).attr('subgo') == 1 || !$(this).attr('subgo')) {
                $(this).attr('subgo', '0');
            } else {
                $(this).attr('subgo', '1');
            }

			var sourceModal = $(this).parents('.source-box').find('span[subgo=1]');
			// var sourceModal =$('.source-box span[subgo=1]')
            if (sourceModal.length > 0) {
                $(this).parent().siblings('.preItem').parent('.sourceItem').addClass('btn-primary').attr('go', 1);
            } else {
                $(this).parent().siblings('.preItem').parent('.sourceItem').removeClass('btn-primary').attr('go', 0);
			}
			if(sourceModal.length < $(this).parents('.source-box').find('span').length){
				$(this).parent().siblings('.preItem').parent('.sourceItem').attr('all', 0)
			}
        })

        /**
         * 鼠标移入
         */
        this.dom.on('mouseover', 'a.sourceItem', function () {
			clearInterval(timer)
			self.dom.find('.source-box').removeClass('show');
            $(this).children('.source-box').addClass('show')
		})

        /**
         * 鼠标移除
         */
		var timer = '';
        this.dom.on('mouseout', 'a.sourceItem', function () {
			var That = this;
			timer = setTimeout(function (){
				$(That).children('.source-box').removeClass('show');
			},200)
            $('.source-box span[subgo=1]');
            var sourceSpan = $(this).children('.source-box').children('span[subgo=1]')
            var sourceSpanAll = $(this).children('.source-box').children('span')

            if (sourceSpan.length > 0 && !parseInt($(this).attr('all'))) {
                $(this).children('.preItem').children('.preNum')[0].textContent = sourceSpan.length + '/' + sourceSpanAll.length;
            } else {
                $(this).children('.preItem').children('.preNum')[0].textContent = '';
            }
		})

        /**
         * 点击收缩
         */
        this.dom.on('click', '.unfoldSource', function () {
            var preId = $(this).attr('preId');
            var tmp = self.sourceTmpArray[preId];
            $(this).parent().append(tmp);
            $(this).remove();
        });

    },
    getReturnSourceData: function () {
        var preDom = Array.prototype.slice.call($('.sourceItem[go=1]'));
        var selectAll = Array.prototype.slice.call($('.sourceItem[all=1]'));
        var sourceIdList = {};
		var dataIdList = [];
		var selectAllData ={};
    if(preDom.length > 0){
		selectAll.forEach(function (item) {
			selectAllData[$(item).attr('dataId')] = true;
		})

        preDom.forEach(function (item) {

            var dataId = $(item).attr('dataId');
            dataIdList.push(dataId);

            var childrenId = [];
            Array.prototype.slice.call($(item).children('.source-box').children('span[subgo=1]')).forEach(function (subItme) {
                childrenId.push($(subItme).attr('subId'))
			});

			if(selectAllData[dataId]){
				sourceIdList[dataId] = 'ALL_SOURCE';
			}else{
				sourceIdList[dataId] = childrenId.join(',');
			}


        });
		// console.log(sourceIdList, dataIdList)


        return [{
            roleIds: dataIdList.join(','),
            type: 1,
            sourceIdList: sourceIdList
        }];
    }else{
        return [{
			type: 1,
			roleIds: -1
		}];
    }

    },
    removeClick: function() {
        $('.source-box span[subgo=1]').removeClass('sourceSubClass').attr('subgo','0');
        $('.sourceItem[go=1]').removeClass('btn-primary').attr('go','0');
        $('.preNum').html('');
    }
}


/***************************************************************
*
* taskId=177 大小渠道显示下拉菜单公共方法
* 说明：请求获取渠道数据，生成渠道下拉列表
* @param data 获取的渠道数据
* @param queryCallback 查询函数（点击渠道时调用）
* @param showEle 显示数据的元素
*
*************************************************************/

function setdropDownList(data, queryCallback, showEle) {
	var showElement=showEle||$('.sourceType')
	var listValue=data.listValue
	var showstatus=showElement.data('statushide');//判断是否展示失效渠道
	var dropHtml = '<li channelId="-1" class="channel"><a>全部渠道</a></li>';
	if(!data.listValue){
		return ;
	}
	listValue.forEach(function (itemObj) {
		if (itemObj.sourceConfigList && itemObj.sourceConfigList.length) {//判断是否有子渠道
			dropHtml += '<li class="dropdown-submenu channel" channelId="' + itemObj.DicCode + '">';
		} else {
			dropHtml += '<li channelId="' + itemObj.DicCode + '" class="channel">';
		}
		dropHtml += '<a>' + itemObj.DicDesc + '</a>'
		// 组织子渠道
		if (itemObj.sourceConfigList && itemObj.sourceConfigList.length) {
			dropHtml += '<ul class="dropdown-menu">'
			for (var i = 0; i < itemObj.sourceConfigList.length; i++) {
				dropHtml += '<li sourceId="' + itemObj.sourceConfigList[i].sourceId + '" channelId="' + itemObj.sourceConfigList[i].
				channelId + '" class="source"><a>' + (itemObj.sourceConfigList[i].name || '未知渠道' )+ '</a></li>'
			}
			dropHtml += '</ul>'
		}
		dropHtml += '</li>'
	})
	$('.channel-menu').html(dropHtml);
	bindSourceClick(showElement, queryCallback, showEle);

}

/**
 * taskId=177 大小渠道显示下拉菜单公共方法
 * 说明：下拉菜单绑定事件，将所选项显，并存储在显示选项的标签中$('.sourceType');
 * 要求：所有用于显示的标签必须包含.sourceType
 * @param contanier 列表的容器 ul JQDOM元素
*/

function bindSourceClick(contanier, queryCallback, showEle) {
	if(showEle){
		var showBtn = showEle;
	}else{
		var showBtn = $('.sourceType');
	}

	contanier.siblings('.channel-menu').on('click','li', function (e) {
		e.stopPropagation();
		if(!$(this).hasClass('disabled')){
			if ($(this).hasClass('channel')) {
				showBtn.attr('channelId', $(this).attr('channelId'));
				showBtn.attr('sourceId', -1);
				showBtn.html($(this).children().html() + ' <span class="caret"></span>');
			} else {
				showBtn.attr('channelId', $(this).attr('channelId'));
				showBtn.attr('sourceId', $(this).attr('sourceId'));
				// 显示格式：大渠道/小渠道
				showBtn.html($(this).parents('li.channel').children('a').text() + '/' + $(this).text() + '<span class="caret"></span>');
			}
			if(queryCallback && showEle){
				queryCallback($(this));
			}else if(queryCallback){
				queryCallback();
			}
			showBtn.dropdown('toggle');
		}

	})
}


/**
 * taskId=177 问答总览显示渠道方法
 * 说明：
 * 要求：
 * getQueListNew 接口中
 * @param data 答案
 * @param sourceList 渠道list
*/


function showNewSource(data, sourceList) {
	var ruleQDHtml = '';//渠道
	var ruleHtml = '';
	if (data.ListRule && data.ListRule[0]) {
		for (var k = 0; k < data.ListRule.length; k++) {
			if (data.ListRule[k].ruleMode == 0) {
				if (data.ListRule[k].type == 1 || data.ListRule[k].type == 3) {
					var roleList = data.ListRule[k].roleIds.split(',');
					roleList.forEach(function (roleItem) {
						sourceList.forEach(function (sourceListItem) {
							if (roleItem == sourceListItem.DicCode) {
								ruleQDHtml += sourceListItem.DicDesc + ',';
							}
						})
					})
				}
			}
		}
	}
	ruleQDHtml = ruleQDHtml.replace(/,$/, '');
	if (ruleQDHtml) {
		ruleHtml += '生效渠道: ' + ruleQDHtml + '<span class="dot">|</span>';
	}
	return ruleHtml;
}



/**
 * taskId=177 问题详情--显示渠道
 * 说明：鼠标移入大渠道- 显示小渠道
 * @param queData 答案的生效渠道
 * @param sourceData 渠道列表
 *
*/

function showSourceRule(queData,sourceData){
	// var sourceData = [];
	// $.ajax({
	// 	url: encodeURI('../../Configuration/listChannelValve'),
	// 	async:false,
	// 	data: {
	// 		itemId: localStorage.getItem('sourceItemId')
	// 	},
	// 	success: function (data) {
	// 		sourceData = data;
	// 	},
	// })

	var channelRuleHtml = '';//渠道
	var ruleHtml = '';
	if (queData.ListRule && queData.ListRule[0]) {
		//queData.ListRule 遍历答案的所有生效渠道
		queData.ListRule.forEach(function(itemObj){
			if(itemObj.ruleMode == 0){
				if (itemObj.type == 1 ||itemObj.type == 3) {
					var roleList =itemObj.roleIds.split(',');
					//roleList遍历目的：拼接大渠道以及小渠道
					roleList.forEach(function (roleItem) {//roleItem 大渠道的id
						//sourceData.listValue遍历目的  将大渠道转为文字显示
						sourceData.listValue.forEach(function (sourceListItem) {//sourceListItem 全部渠道的对象
							if (roleItem == sourceListItem.DicCode) {
								channelRuleHtml +='<li>'+ sourceListItem.DicDesc ;
								//加载大渠道下的小渠道 --全部渠道 小渠道数据在/Configuration/listChannelValve接口中
								if(itemObj.type == 3 || (itemObj.type == 1 && $.isEmptyObject(itemObj.sourceMap[roleItem]))){
									var sourceHtml='<ul class="source-contanier">';
									sourceListItem.sourceConfigList.forEach(function(child){
										sourceHtml += ' <li>'+(child.name || '未知渠道')+'</li> ';
									})
									channelRuleHtml += sourceHtml + '</ul></li>';
								}
							}

							// channelRuleHtml += '</li>';

						})

						//加载大渠道下的小渠道 --非全渠道
						if(itemObj.type == 1 && !$.isEmptyObject(itemObj.sourceMap[roleItem])){
							var sourceHtml='<ul class="source-contanier">';
							itemObj.sourceMap[roleItem].forEach(function(child){
								sourceHtml += ' <li>'+(child.sourceName || '未知渠道')+'</li> ';
							})
							channelRuleHtml += sourceHtml + '</ul></li>';
						}
					})
				}
			}
		})
	}
	if (channelRuleHtml) {
		ruleHtml += '生效渠道: ' +'<ul class="channel-contanier">' +channelRuleHtml +'</ul>' +'<span class="dot">|</span>';
	}
	return ruleHtml;
}
/**
 * 鼠标移入大渠道显示小渠道
 * */

function hoverShowSource(){
	$('.channel-contanier>li').on('mouseenter',function(){
		$('.source-contanier').hide();
		$(this).find('.source-contanier').show();
	})
	$('.channel-contanier>li').on('mouseout',function(){
		$(this).find('.source-contanier').hide();
	})
}

/*************************************************************
 *                    选择渠道公共方法                        *
 * showModal() 显示模态框
 * hideModal() 删除模态框
 * submitCallBack(fn) 点击确定获取选中渠道数据回调方法
 * setBackFill() 回填已选中渠道数据
 * 例子：
 *     var sourceModel = new SourceModel();
 *     sourceModel.showModal();// 显示模态框
 *     sourceModel.submitCallBack(function(data) {console.log(data)}) // 点击确定回调
 *     sourceModel.setBackFill(Array)  //回填（数组格式,返回已选渠道的字符串）
 * 回填格式：[
               {
                roleIds:'0',  // 父级id 字符串隔开 '0,1,2,3'
				ruleMode: '维度类型' ,
				type:  1,
                sourceMap:{ // 子集id 数组  如果为字符串'ALL_SOURCE'为全选所有子集
                    0:[
                        { sourceId:149, souceName:'云问网页2'},
                        { sourceId:149, souceName:'云问网页2' }
                    ],
                    1: 'ALL_SOURCE'
                }
               }
            ]
 *
 *************************************************************/
function SourceModel(sourceStatus) {//sourceStatus为true时隐藏状态禁用的渠道
	this.sourceStatus=sourceStatus||false
	this.tempModel = '';
	var sourceItemId = localStorage.getItem('sourceItemId');
	this.sourceItemId = sourceItemId || 1669;
	this.callBackArray = [];
	this.backFillData = [];
	this.isFill = false;
	this.isRequestSuccess = false;
	this.sendObj = {};
	this.init();
}

SourceModel.prototype = {
	init: function () {
		// this.createSourceModal();
		this.getSourceData(this.sourceItemId);
	},
    /**
     * 创建模态框
     */
	createSourceModal: function (content) {
		var tmp =
			'<div class="sourceModal modal fade bs-example-modal-lg" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel">' +
			'<div class="modal-dialog" role="document">' +
			'<div class="modal-content">' +
			'<div class="modal-header">' +
			'<button type="button" class="close cancel" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>' +
			'<h4 class="modal-title" id="myModalLabel">选择渠道</h4>' +
			'</div>' +

			'<div class="modal-body">' +
			'<p class="SourceModalZS" style="color:#242a30">注：不勾选任何渠道为全渠道生效</p>'+
			'<ul class="nav sourceData">' +
			content +
			'</ul>' +
			'</div>' +

			'<div class="modal-footer">' +
			'<button type="button" class="btn btn-primary submitSource">确定</button>' +
			'<button type="button" class="btn btn-default cancel" data-dismiss="modal">取消</button>' +
			'</div>' +
			'</div>' +
			'</div>' +
			'</div>'
		$('body').append(tmp);
	},
    /**
     * 显示模态框方法
     */
	showModal: function () {
		var self = this;
		$('.sourceModal').modal('show');
	},
    /**
     * 删除模态框方法
     */
	hideModal: function () {
		$('.sourceModal').modal('hide');

	},
    /**
     * 获取渠道数据
     */
	getSourceData: function (sourceItemId) {
		// http://{{hostname}}/Configuration/listChannelValve
		var self = this;
		$.ajax({
			dataType: 'json',
			url: '../../Configuration/listChannelValve?itemId=' + sourceItemId,
			async:false,
			success: function (data) {
				// if(data.code === 200){
				self.isRequestSuccess = true;
				// console.log(data);
				self.createSourceModal(self.getSourceDataTmp(data.listValue))
				self.setDomListenEvent();
				self.setSubmitSource();

				$('.sourceModal').on('show.bs.modal', function () {
					self.showFillEcecute(self.sendObj);
				})

				$('.sourceModal').on('hide.bs.modal', function () {
					$('.sourceModal input[type=checkbox]').removeAttr('checked');
				})

				// 如果在渠道数据加载前回填，及再执行一次；
				if (!self.isFill) {
					self.backFillExecute();
				}
				// }
			}
		});
	},

    /**
     * 获取渠道数据内容模版
     */
	getSourceDataTmp: function (data) {
		var tmp = '';
		var self=this;
		if(!data) { return ''}
		data.forEach(function (item) {
			if(self.sourceStatus){
				var statusFlag=true
				for(var i=0;i<item.sourceConfigList.length;i++){
					if(item.sourceConfigList[i].status==0){
						statusFlag=false
						continue;
					}
				}
				if(statusFlag){
					return true;
				}
			}
			// 父级
			tmp += '<li>' +
				'<span>' +
				'<label><input name="parent" dataId="' + item.DicCode + '" type="checkbox" data-render="switchery" value="' + item.DicDesc + '"/>' + item.DicDesc + '</label>' +
				'</span>';
			// 子级
			if(item.sourceConfigList){
				item.sourceConfigList.forEach(function (children) {
					if(self.sourceStatus&&children.status){
						return true;
					}
					tmp += '<ul class="nav childern">' +
						'<li>' +
						'<label>' +
						'<input dataChildren="' + children.sourceId + '" channelId="' + children.channelId + '" name="childern" type="checkbox" data-render="switchery" value="' + (children.name || '未知渠道' )+'" data-status="'+children.status+'"/>' +
						(children.name || '未知渠道' ) +
						'</label>' +
						'</li>' +
						'</ul>';
				});
			}

			// 结尾
			tmp += '</li>';
		})
		if(tmp){
			return tmp
		}else{
			return '<div style="text-align:center">未设置生效渠道！</div>'
		}
	},
    /**
     * 添加选中事件
     */
	setDomListenEvent: function () {
		$('.sourceModal').on('click', 'input:checkbox', function () {
			var selfDom = $(this);
			var parentId = selfDom.attr('dataId');
			var childrenId = selfDom.attr('dataChildren');
			var channelId = selfDom.attr('channelId');
			// 父级
			if (parentId) {
				if (selfDom.attr('checked')) {
					$('.sourceModal input[channelId="' + parentId + '"]').attr('checked', 'checked');
				} else {
					$('.sourceModal input[channelId="' + parentId + '"]').removeAttr('checked');
				}
			} else if (childrenId && channelId) {
				var checkedChildernDom = $('.sourceModal input[name="childern"][channelId="' + channelId + '"]:checked');
				var allChildernDom = $('.sourceModal input[name="childern"][channelId="' + channelId + '"]');
				if (checkedChildernDom.length < allChildernDom.length) {
					$('.sourceModal input[dataId="' + channelId + '"]').removeAttr('checked');
				}
				// else if (checkedChildernDom.length == allChildernDom.length) {
				// 	$('.sourceModal input[dataId="' + channelId + '"]').attr('checked', 'checked');
				// }
				// 已选子元素则给父级增加标记
				if (checkedChildernDom.length > 0) {
					$('.sourceModal input[dataId="' + channelId + '"]').addClass('hasChild');
				} else {
					$('.sourceModal input[dataId="' + channelId + '"]').removeClass('hasChild');
				}
			}
		});
	},

    /**
     * 添加确定事件
     */
	setSubmitSource: function () {
		var self = this;
		$('.sourceModal').on('click', '.submitSource', function () {
			var data = {};
			var allSelect = Array.prototype.slice.call($('.sourceModal input[name=parent]:checked'));
			var parentArray = Array.prototype.slice.call($('.sourceModal input[name=parent]:checked,.sourceModal input[name=parent].hasChild'));
			var parentData = [];
			var allSelectData = {};
			var childrenData = {};
			var parentName = [];
			var selectList = {};//保存已选的大小渠道名称
			var selectStr = '';//保存已选的大小渠道名称转为字符串

			self.isClicksubmit = true;

			parentArray.forEach(function (dom) {
				parentData.push($(dom).attr('dataId'));
				parentName.push($(dom).val());
			});

			//获取渠道全选的元素
			allSelect.forEach(function (dom){
				allSelectData[$(dom).attr('dataId')] = true;
			})

			parentData.forEach(function (parentId, index) {
				var childrenList = Array.prototype.slice.call($(('.sourceModal input[name=childern][channelId=' + parentId + ']:checked')));
				var allChildernListLen = Array.prototype.slice.call($(('.sourceModal input[name=childern][channelId=' + parentId + ']'))).length;
				var arrayId = [];
				var childrenName = [];//小渠道的名称

				childrenList.forEach(function (dom) {
					arrayId.push($(dom).attr('dataChildren'));
					childrenName.push($(dom).val())
				})

				// childrenData.push({
				//     [parentId]:arrayId.join(',')
				// })
				if (allSelectData [parentId]) {
					childrenData[parentId] = 'ALL_SOURCE';
				} else {
					childrenData[parentId] = arrayId.join(',')
				}


				//保存已选择的大小渠道名称
				if (childrenData[parentId] == 'ALL_SOURCE') {
					selectList[parentName[index]] = '全渠道';
				} else {
					selectList[parentName[index]] = childrenName;
				}
			})

			//转为字符串显示在input框中
			for (var key in selectList) {
				if (selectList[key] == '全渠道') {
					selectStr += key + '- 全渠道'
				} else if (selectList[key].length == 0) {
					continue;
				} else {
					selectList[key].forEach(function (child, index) {
						if (index == selectList[key].length - 1) {
							selectStr += key + '-' + child;
						} else {
							selectStr += key + '-' + child + ',';
						}
					})
				}
				selectStr += ";"
			}

			self.callBackArray.forEach(function (callback) {
				self.sendObj = {
					type: 1,
					roleIds: parentData.join(','),
					sourceIdList: childrenData
				}
				callback({
					sourceList: self.sendObj,
					selectItem: selectStr
				});
			})

			self.hideModal();

		})
	},
    /**
     * 确定回调事件
     */
	submitCallBack: function (fn) {
		this.callBackArray = [];
		this.callBackArray.push(fn);
	},
    /**
     * 回填渠道数据fn
	 * @param data 问题的生效渠道
	 * 返回已选渠道的字符串
     */
	setBackFill: function (data, inputEle) {
		this.backFillData = data;
		this.backFillExecute(inputEle);
		// taskid =413 修改问题时，不更改渠道时，清除原始渠道bug
		this.showFillEcecute(this.sendObj);
		$('.submitSource').click();
	},

	setBackFillNew: function (data, inputEle) {
		this.backFillData = data;
		this.backFillExecute(inputEle);
		// taskid =413 修改问题时，不更改渠道时，清除原始渠道bug
		this.showFillEcecute(this.sendObj);
	},

	/**
		 * 	数据回填的同时将回填的数据转为发送的类型，方便模态框显示的回填（发送的数据格式），放入this.sendObj中
		 * 发送的数据格式：
		* {
			roleIds:'0',  // 父级id 字符串隔开 '0,1,2,3'
			type:  1,
			sourceIdList:{ // 子集id 对象  如果为字符串'ALL_SOURCE'为全选所有子集
				0:{
					'149','149'，'149'
				},
				1：'ALL_SOURCE'
			}

		*
		*/
	backFillExecute: function (inputEle) {
		if (!$.isEmptyObject(this.backFillData) && this.isRequestSuccess) {
			this.isFill = true;
			// this.backFillData.forEach(function (item) {
			//     if(item.type == '1' || item.type == '3'){
			//         var parentList = item.roleIds.split(',');
			//         parentList.forEach(function (parentId) {
			//             $('.sourceModal input[name="parent"][dataid="'+parentId+'"]').attr('checked','checked');

			//             // 选中子集
			//             var childern = item.sourceMap[parentId];
			//             if(typeof(childern) == 'string'){
			//                 if(childern == 'ALL_SOURCE'){
			//                     $(('.sourceModal input[name=childern][channelId="'+parentId+'"]')).attr('checked','checked')
			//                 }
			//             }else{
			//                 childern.forEach(function (childernItem) {
			//                     $(('.sourceModal input[name=childern][dataChildren="'+childernItem.sourceId+'"]')).attr('checked','checked')
			//                 })
			//             }

			//         })
			//     }
			// })

			if (this.backFillData.type == '1' || this.backFillData.type == '3') {
				var parentList = this.backFillData.roleIds.split(',');
				var self = this;
				var inputStr = '';

				self.sendObj = {
					type: 1,
					roleIds: this.backFillData.roleIds,
					sourceIdList: {}
				}
				parentList.forEach(function (parentId) {
					// 选中子集
					var parentId = parseInt(parentId);
					var childern = self.backFillData.sourceMap[parentId];
					var childrenData = [];
					if (typeof (childern) == 'string' || $.isEmptyObject(self.backFillData.sourceMap)) {
						if (childern == 'ALL_SOURCE' || $.isEmptyObject(self.backFillData.sourceMap)) {
							$('.sourceModal input[name="parent"][dataid="' + parentId + '"]').attr('checked', 'checked');
							$(('.sourceModal input[name=childern][channelId="' + parentId + '"]')).attr('checked', 'checked')
							childrenData = 'ALL_SOURCE';
							inputStr += $('.sourceModal input[dataId="' + parentId + '"]').val() + '-' + '全渠道,';
						}
					} else {
						childern.forEach(function (childernItem) {
							$(('.sourceModal input[name=childern][dataChildren="' + childernItem.sourceId + '"]')).attr('checked', 'checked')
							childrenData += childernItem.sourceId + ',';
							inputStr += $('.sourceModal input[dataId="' + parentId + '"]').val() + '-' + childernItem.sourceName + ',';

						})
					}
					self.sendObj.sourceIdList[parentId] = childrenData.replace(/,$/, '');
					inputStr = inputStr.replace(/,$/, ';');
				})
			}
			// return inputStr;
			if(inputEle){
				inputEle.val(inputStr);
			}
		}
	},
	/**
	 * 模态框显示时回填数据
	*/

	showFillEcecute: function (data) {
		if (!$.isEmptyObject(data)) {
			if (data.type == '1' || data.type == '3') {
				var parentList = data.roleIds.split(',');
				if(!parentList[0]){
					return;
				}
				parentList.forEach(function (parentId) {
					var parentId = parseInt(parentId);
					if (data.sourceIdList[parentId] == 'ALL_SOURCE' ) {
						$('.sourceModal input[name="parent"][dataid="' + parentId + '"]').attr('checked', 'checked');
						$(('.sourceModal input[name=childern][channelId="' + parentId + '"]')).attr('checked', 'checked');
					} else {
						var childern = data.sourceIdList[parentId].split(',');
						$('.sourceModal input[dataId="' + parentId + '"]').addClass('hasChild');
						childern.forEach(function (childernItem) {
							$(('.sourceModal input[name=childern][dataChildren="' + childernItem + '"]')).attr('checked', 'checked')
						})
					}
				})
				// 选中子集
				// for(var i=0 ;i<data.sourceIdList.length;i++){
				// 	var item=data.sourceIdList[i];
				// 	var key=Object.keys(item);
				// 	if(item[key]){
				// 		var childern = item[key].split(',');
				// 		if(childern.length == $('.sourceModal input[name=childern][channelId="'+key+'"]').length){
				// 			$('.sourceModal input[name="parent"][dataid="'+key+'"]').attr('checked','checked');
				// 			$(('.sourceModal input[name=childern][channelId="'+key+'"]')).attr('checked','checked');
				// 		}else{
				// 			childern.forEach(function (childernItem) {
				// 				$(('.sourceModal input[name=childern][dataChildren="'+childernItem+'"]')).attr('checked','checked')
				// 			})
				// 		}
				// 	}else if(item[key] == ''){
				// 		$('.sourceModal input[name="parent"][dataid="'+key+'"]').attr('checked','checked');
				// 	}
				// }
				// })
			}
		}

	},
	/**
	 * 清空已填写的数据
	*/
	clearSourceData: function () {
		$('.sourceModal input[type=checkbox]').removeAttr('checked');
		// $('.sourceModal input[type=checkbox]').removeClass('hasChild');
		this.sendObj = {};
	},
}
/*************************************************************
 *                    模态框选择渠道公共方法 结束
 *  *
 *************************************************************/

 /***
  * 列表中显示渠道信息：大渠道-小渠道
 */
function sourceInfoInTable (channel,source){
	var roleHtml = "未知渠道"
	if(channel && source){
		roleHtml = channel + '-' + source;
	}else if(channel){
		roleHtml = channel;
	}else if(source){
		roleHtml = source;
	}
	return roleHtml;
}


/**
* 切换确认按钮状态，变为loading状态(不可点击)
*/

var THROTTLE_STORE = {
	disabled: false,
	text: '确认'
}

function useThrottle (options) {
	// options.classname 目标dom的class名，可重命名
	// options.disabled 是否禁用

	var name = '.throttle'
	if (options && options.classname) {
		name = options.classname // 接受重命名
	}
	var ele = $(name)

	if (options && options.disabled !== undefined) {
		if (options.disabled === true && THROTTLE_STORE.disabled === false) {
			THROTTLE_STORE.disabled = true
			if (options.text) THROTTLE_STORE.text = options.text
			ele.empty()
			ele.addClass('throttle-active throttle-disabled')
		} else if (options.disabled === true && THROTTLE_STORE.disabled === true) {
			return false
		} else if (options.disabled === false) {
			THROTTLE_STORE.disabled = false
			ele.text(THROTTLE_STORE.text)
			ele.removeClass('throttle-active throttle-disabled')
		}

		return true
	}
}
/*********************
 * 分页切换页码时保存当前页码
 * 一般用于删除或修改数据后仍然保存在当前页
 * pageId:代表展示分页的元素的Id
 * 示例：saveCurrPage('itemContainer')
 * *****************/
function saveCurrPage(pageId){
	var page = '';
	if(pageId){
		page = $('#' + pageId + ' .active a').html()
	}else{
		page = 1;
	}
	return page;
}

/*
  全屏遮罩
  使用方法：在最外层页面的底部添加dom结构：

  <div id="full-screen-loading"></div>

  调用queryAll函数会自动加载loading: data/js/util.js

  需要引入css文件: web/common/css/commonCSS.css
*/
function toggleFullScreenLoading (bool) {
	var target = $('#full-screen-loading')
	target.empty()
	target.append('<div class="ajax-spinner-bars"><div class="bar-1"></div><div class="bar-2"></div><div class="bar-3"></div><div class="bar-4"></div><div class="bar-5"></div><div class="bar-6"></div><div class="bar-7"></div><div class="bar-8"></div><div class="bar-9"></div><div class="bar-10"></div><div class="bar-11"></div><div class="bar-12"></div><div class="bar-13"></div><div class="bar-14"></div><div class="bar-15"></div><div class="bar-16"></div></div>')
	if (bool) {
	  target.css('display', 'block')
	} else {
	  target.css('display', 'none')
	}
  }